// 提供工具函数

// 定义一个处理时间的函数
// 参数说明
//     // 当传入参数是时间戳
//     datetime = new Date()
//     datetime.setTime(time)  // 主要利用这个方法
export function moment(time, length) {
    // console.log(time);
    // 当传入参数是 2021-11-23T06:29:11.699Z 或 时间戳
    let datetime = null
    if (time !== -1) {
        datetime = new Date(time)
        // console.log(datetime);
    } else {
        datetime = new Date()
    }
    let year = datetime.getFullYear()
    let month = datetime.getMonth() + 1
    let date = datetime.getDate()
    let hour = datetime.getHours()
    if (hour <= 9) {
        hour = '0' + hour
    }
    let minute = datetime.getMinutes()
    if (minute <= 9) {
        minute = '0' + minute
    }
    let second = datetime.getSeconds()
    if (second <= 9) {
        second = '0' + second
    }

    if (length == 3) {
        return year + '-' + month + '-' + date
    }
    // let mseconds = datetime.getMilliseconds();
    return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second //+"."+mseconds;
}

// 定义一个根据当前路由信息来处理面包削显示参数的函数
export function handleTitle(val) {
    // val 当前路由
    for (let i = 0; i < menulist.length; i++) {
        for (let j = 0; j < menulist[i].children.length; j++) {
            if (menulist[i].children[j].path == val) {
                return {
                    title1: menulist[i].label,
                    title2: menulist[i].children[j].label,
                }
            }
        }
    }
}

// 差值排除
// arr2大数组 arr1小数组
export function filterArray(arr2, arr1) {
    return arr2.filter((item) => !arr1.some((itey) => itey.id === item.id))
}

// 比教两个数组前n项是否相同
export function isSomeArr(arr1, arr2, index) {
    let result = true
    for (let i = 0; i < index; i++) {
        if (arr1[i] !== arr2[i]) {
            result = false
            break
        }
    }
    return result
}

export function addZelo(val) {
    return val > 9 ? val : '0' + val
}

// 处理时间
// 返回示例 4个月前 (11/12) 21:41
// 传入time示例  2022-03-11T16:23:12.764Z
export function myTime(time, type = 0) {
    if (!time) {
        return '---'
    }
    let date = ''
    if (type === 0 || type === 2) {
        date = new Date(time)
    }
    // 获取当前时间戳
    let now = new Date().getTime()
    // 获取传入时间戳
    let old = new Date(time).getTime()
    // 获取时间差
    let diff = now - old
    // 返回 **前
    let oneYear = 60 * 60 * 24 * 365 * 1000
    let arr = [
        60 * 1000,
        60 * 60 * 1000,
        60 * 60 * 24 * 1000,
        60 * 60 * 24 * 7 * 1000,
        60 * 60 * 24 * 30 * 1000,
        oneYear,
    ]
    let str_obj = ['分钟', '小时', '天', '周', '月', '年']
    let str = ''

    if (diff >= oneYear) {
        return Math.floor(diff / oneYear) + '年前'
    }
    for (let i = 0; i < arr.length; i++) {
        if (diff < arr[i]) {
            // 向上取整
            if (i == 0) {
                return '1分钟前'
            }
            str = Math.ceil(diff / arr[i - 1]) + str_obj[i - 1] + '前'
            break
        }
    }

    return str
}

// 颜色
export function LightDarkenColor(color, num = 50) {
    color = color.replace('#', '')
    // 分组
    let arr1 = color.split('')
    let arr2 = []
    arr1.forEach((_, index) => {
        if (index % 2 === 0) {
            arr2.push(color.slice(index, index + 2))
        }
    })

    let sColorChange = []

    for (let i = 0; i < arr2.length; i++) {
        let current_number = parseInt(arr2[i], 16) // 16 => 10
        let val = current_number + num
        if (val < 0) {
            val = 0
        }
        if (val > 255) {
            val = 255
        }
        sColorChange.push(eval(val).toString(16)) // 10 => 16
    }
    return '#' + sColorChange.join('')
}

// 背景色
export function LightDarkenBgColor(color, num = 0.1) {
    color = color.replace('#', '')
    // 分组
    let arr1 = color.split('')
    let arr2 = []
    arr1.forEach((_, index) => {
        if (index % 2 === 0) {
            arr2.push(color.slice(index, index + 2))
        }
    })

    let sColorChange = []

    for (let i = 0; i < arr2.length; i++) {
        let current_number = parseInt(arr2[i], 16) // 16 => 10
        let val = current_number
        if (val < 0) {
            val = 0
        }
        if (val > 255) {
            val = 255
        }
        sColorChange.push(val) // 10 => 16
    }

    return `rgba(${sColorChange.join(',')},${num})`
}

// 平滑滚动方式
export function betterScroll(el, to) {
    let oldscrollTop = el.scrollTop
    let timer = setInterval(() => {
        let scrollTop = el.scrollTop
        if (oldscrollTop <= to) {
            let sleep = Math.ceil((to - scrollTop) / 20)
            if (scrollTop < to) {
                if (scrollTop + sleep >= to) {
                    el.scrollTop = to
                    return
                }
                el.scrollTop = scrollTop + sleep
            } else {
                clearInterval(timer)
                timer = null
            }
        } else {
            let sleep = Math.floor((to - scrollTop) / 5)
            if (scrollTop > to) {
                if (scrollTop + sleep <= to) {
                    el.scrollTop = to
                    return
                }
                el.scrollTop = scrollTop + sleep
            } else {
                clearInterval(timer)
                timer = null
            }
        }
    }, 20)
}

/**
 * 数组按照下面的顺序排序返回
 * oldArr 原数组
 * sortArr 排序数组
 * key  排序key
 * ***/
export function sortArray(oldArr, sortArr, key) {
    if (!Array.isArray(oldArr) || !Array.isArray(sortArr) || !key) {
        console.warn('sortArray传入参数错误')
        return oldArr
    }
    let obj = {}
    // 创建基本数组
    sortArr.forEach((item) => {
        obj[item] = []
    })

    oldArr.forEach((item) => {
        obj[item[key]].push(item)
    })
    let newArr = []
    sortArr.forEach((item) => {
        newArr = [...newArr, ...obj[item]]
    })

    return newArr
}
// 文件限制
export function fileLimit(file, options = {}) {
    let { maxSize } = options
    let size = file.size / 1024

    // 判断大小
    if (maxSize) {
        if (size > maxSize) {
            return Promise.resolve(`文件大小不能超过${maxSize}KB`)
        }
    }

    return Promise.resolve('')
}

// isios()
export const isIOS = () => {
    return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
}

/**
 * 通过年月获取当月的天数
 * y 年
 * m 月
 * **/
export function getMonthDays(y, m) {
    let d = new Date(y, m, 0)
    return d.getDate()
}

// klWow
export function klWow() {
    const getType = (val) => {
        return Object.prototype.toString
            .call(val)
            .match(/\s.+/g)[0]
            .replace(/\]/g, '')
            .replace(/\[/g, '')
            .replace(/\s+/g, '')
            .toLowerCase()
    }
    let params = arguments[0]
    // 判断类型是否是对象
    let type = getType(params)
    if (!['object'].includes(type)) {
        return new Error('参数必须是对象')
    }
    let {
        el, // 被监听的节点
        scrollContainer, // 滚动容器
        defaultAnimate, // 默认是否有动画
        infinite, // 是否每次滚动都执行
    } = params

    el = params.el || '.kl-wow'
    scrollContainer = scrollContainer || 'body'
    defaultAnimate = defaultAnimate === false ? false : true
    infinite = infinite === false ? false : true

    const scrollEvent = () => {
        let els = document.querySelectorAll(el)
        let scrollContainerEl = document.querySelector(scrollContainer)
        if (els.length === 0 || !scrollContainerEl) {
            return
        }

        for (let i = 0; i < els.length; i++) {
            let el = els[i]
            let el_top = el.getBoundingClientRect().top
            let scrollContainerEl_top = scrollContainerEl.getBoundingClientRect().top
            let scrollContainerEl_height = scrollContainerEl.clientHeight
            if (el_top > 0 && el_top - scrollContainerEl_top < scrollContainerEl_height) {
                // 进入可视区域
                let animate = el.getAttribute('data-animate') || 'fadeInUp'
                el.classList.add(animate)
            } else {
                if (infinite) {
                    let animate = el.getAttribute('data-animate') || 'fadeInUp'
                    el.classList.remove(animate)
                }
            }
        }
    }
    // 初始化
    if (defaultAnimate) {
        scrollEvent()
    }

    // 滚动事件
    let scrollContainerEl = document.querySelector(scrollContainer)
    if (!scrollContainerEl) {
        return
    }
    scrollContainerEl.addEventListener('scroll', scrollEvent)
}

// 加密
export function encodeParams(str) {
    try {
        str = encodeURIComponent(str)
        window.btoa(str)
        return str
    } catch (e) {
        return null
    }
}




// 解密
export function decodeParams(str) {
    if (typeof str !== 'string') {
        return null
    }
    try {
        str = window.atob(str)
        str = decodeURIComponent(str)
        return str
    } catch (e) {
        return null
    }
}

/**
 * 懒加载方法
 * el img类名
 * scroll_el 滚动区域类名
 * number预先加载距离 值越大，越早加载
 * **/
export function lazyLoad({ el = 'lazy-img', scroll_el, number = 100 }) {
    if (!scroll_el) {
        scroll_el = window
    } else {
        scroll_el = document.querySelector(scroll_el)
    }
    let els = document.querySelectorAll(el)
    // scroll_el 距离顶部的距离
    let length = els.length

    if (length > 0) {
        // 定义一个节流函数
        let time1 = 0
        let n = 0 // 优化滚动时的次数
        const trolttle = (func, time = 200) => {
            let time2 = Date.now()
            if (time2 - time1 > time) {
                time1 = time2
                func()
            }
        }
        // 懒加载核心
        const scrollLazy = () => {
            // 获取scroll_el 距离顶部的距离
            let scroll_el_top = scroll_el.getBoundingClientRect().top
            // 滚动区域高度
            let viewH = scroll_el.clientHeight
            for (let i = n; i < length; i++) {
                let el_img = els[i]
                let el_img_top = el_img.getBoundingClientRect().top
                if (el_img_top - scroll_el_top - number < viewH) {
                    // 获取data-src的值
                    let data_src = el_img.getAttribute('data-src')
                    if (data_src) {
                        el_img.src = data_src
                        n++
                    }
                }
            }
        }

        scrollLazy()
        // 监听滚动事件
        scroll_el.addEventListener('scroll', () => {
            trolttle(scrollLazy, 300)
        })
    }
}

// 判断文件大小
export function isFileSize(file, size = 10) {
    if (!file || !file.size) {
        return '文件不存在'
    }

    let fileSize = file.size / 1024 / 1024
    if (fileSize > size) {
        return `文件大小不能超过${size}M`
    }
}

// 判断文件类型
export function isFileType(file, arr) {
    let name = file.name?.toLowerCase() || ''
    let type = name.substring(name.lastIndexOf('.') + 1)

    if (!type) {
        return '文件类型不存在'
    }
    if (!arr.includes(type)) {
        return `文件类型不正确,请上传${arr.join('、')}类型的文件`
    }
}

// ctrl-f效果
export function handleCtrlF(content = '', f_dom = 'body', c_dom = ['strong', 'h1', 'h2', 'h3']) {
    if (content.length > 0 && Array.isArray(c_dom) && c_dom.length > 0) {
        content = content.toLowerCase()
        // 先要清除原来的
        let els = $('.active-ctrl-mo-bg')
        if (els.length > 0) {
            for (let i = 0; i < els.length; i++) {
                let content = els.eq(i).html()
                // replaceWith() 方法用指定的 HTML 内容或元素替换被选元素
                els.eq(i).replaceWith(content)
            }
        }

        // 绑定新的
        for (let i = 0; i < c_dom.length; i++) {
            let allDomTop = []
            let domStr = c_dom[i]
            let regExp = new RegExp(content, 'g')

            $(f_dom + ' ' + domStr).each(function () {
                let html = $(this).html().toLowerCase()
                //不包含隐藏的HTML
                if (content.indexOf(content) >= 0 && html.indexOf(content) >= 0) {
                    if (
                        !content.includes('search-height-light-class') ||
                        $(this)[0].children.length == 0
                    ) {
                        let id = 'wxj-' + createId()
                        if ($(this) && $(this).offset()) {
                            let obj = {
                                id,
                            }

                            allDomTop.push(obj)

                            // 替换为高亮节点
                            let newHtml = html.replace(
                                regExp,
                                `<font id='${id}' class="active-ctrl-mo-bg">` + content + '</font>',
                            )
                            $(this).html(newHtml)
                        }
                    }
                }
            })
        }
    }
}

// base64 => blob
export function base64ToBlob(base64, fileName) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
}

// blob => file
export function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date()
    theBlob.name = fileName
    return theBlob
}
